<template>
  <!--  委外-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="物料" style="width: 250px" prop="materalId">
          <el-select v-model="searchParam.materialId" placeholder="请选择物料" filterable @change="handleTeamChange">
            <el-option v-for="(item, index) of materialList" :key="index" :label="item.materialName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" style="width: 250px" prop="materalId">
          <el-select v-model="searchParam.status" placeholder="请选择类型" filterable clearable>
            <el-option label="出库" :value="0"/>
            <el-option label="入库" :value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="入库仓库" style="width: 250px" prop="wareId">
          <el-tree-select v-model="searchParam.wareId" :data="wareList" check-strictly filterable clearable
                          :render-after-expand="false" :props="{
							children: 'sonList',
							label: 'warehouseName',
							value: 'id',
						}" style="width: 250px" @change="wareChange"/>
        </el-form-item>

        <el-form-item label="入库库位">
          <el-select v-model="searchParam.targetStorageId" placeholder="请选择" clearable filterable multiple collapse-tags
                     collapse-tags-tooltip
                     :max-collapse-tags="2" style="width: 300px">
            <el-option v-for="item in storageList" :key="item.id" :label="item.storageName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="出库仓库" style="width: 250px" prop="wareId">
          <el-tree-select v-model="searchParam.wareId2" :data="wareList" check-strictly filterable clearable
                          :render-after-expand="false" :props="{
							children: 'sonList',
							label: 'warehouseName',
							value: 'id',
						}" style="width: 250px" @change="wareChange2"/>
        </el-form-item>
        <el-form-item label="出库库位">
          <el-select v-model="searchParam.sourceStorageId" placeholder="请选择" clearable filterable multiple collapse-tags
                     collapse-tags-tooltip
                     :max-collapse-tags="2" style="width: 300px">
            <el-option v-for="item in sourceStorageId_out" :key="item.id" :label="item.storageName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="计划时间">
          <el-date-picker v-model="searchParam.times" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
                          range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" style="width: 400px;"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button icon="Download" type="primary" :loading="downLoading" @click="handleExport"
                     style="margin-left: 10px;">导出
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" :summary-method="getSummaries"
                show-summary border height="calc(100vh - 370px)">
        <el-table-column label="序号" align="center" width="70" fixed>
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{
              (pageSearch.current - 1) * pageSearch.pageSize +
              scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="materialNo" label="物料编码" align="center" min-width="250" fixed show-overflow-tooltip/>
        <el-table-column prop="materialName" label="物料名称" align="center" min-width="250" show-overflow-tooltip/>
        <!-- <el-table-column prop="version" label="物料版本" align="center" min-width="200" /> -->
        <el-table-column prop="batchNo" label="物料二维码" align="center" min-width="200"/>
        <el-table-column prop="traceCode" label="追溯码" align="center" min-width="250"/>
        <el-table-column prop="materialCount" label="数量" align="center" min-width="200"/>
        <el-table-column prop="materialWeigh" label="次单位数量" align="center" min-width="200"/>
        <el-table-column prop="supplierName" label="供应商" align="center" min-width="200" show-overflow-tooltip/>
        <!-- <el-table-column prop="quality" label="有效期(天)" align="center" min-width="200" /> -->
        <!-- <el-table-column prop="quality" label="入库订单号" align="center" min-width="200" /> -->
        <!-- <el-table-column prop="quality" label="入库仓库" align="center" min-width="200" /> -->
        <el-table-column prop="targetStorageName" label="入库库位" align="center" min-width="200"/>
        <el-table-column prop="sourceStorageName" label="出库库位" align="center" min-width="200"/>
        <el-table-column label="状态" prop="status" align="center" min-width="100" :formatter="formatStatus"/>
        <!-- <el-table-column prop="batch" label="入库批次" align="center" min-width="200" /> -->
        <el-table-column prop="createTime" label="创建时间" align="center" min-width="200"/>
        <el-table-column prop="createName" label="创建人" align="center" min-width="200"/>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
                       :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {computed, reactive, ref} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus, Refresh, Search} from '@element-plus/icons-vue';
import axios from "axios";
import moment from "moment";

onMounted(() => {
  getList();
  getOption();
});


const pageSearch = ref({
  current: 1,
  pageSize: 10
});


const workOrderList = ref({});
const wareList = ref([]);
const formatStatus = (row, column, cellValue) => {
  switch (cellValue) {
    case 0:
      return '出库';
    case 1:
      return '入库';
  }
};

const pageTotal = ref(null);//页面总数
const searchParam = ref({});//页面检索条件

// 合计方法
const getSummaries = (param) => {
  const {columns, data} = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'; // 第一列显示“合计”
      return;
    }
    if (column.property === 'materialCount') {
      // 计算数量列的合计
      const values = data.map((item) => Number(item[column.property]));
      sums[index] = values.reduce((prev, curr) => {
        return prev + curr;
      }, 0);
    } else {
      sums[index] = ''; // 其他列留空
    }
  });
  return sums;
};

// 判断质检类型
const getQualityTypeByValue = (e) => {
  let name = null;
  for (const item of qualityTypeList) {
    if (e == item.value) {
      name = item.label;
    }
  }
  return name;
};

// 质检类型
const qualityTypeList = reactive([
  {
    label: '部分送货',
    value: '1'
  },
  {
    label: '全部送货',
    value: '2'
  },
  {
    label: '未送货',
    value: '0'
  }
  // 继续添加更多检查类型...
]);


const paginatedData = ref([]);
const materiaList = ref([]);//物料表
const procedureOrderList = ref([]);//工序订单
const supplierList = ref([]);
const storageAllList = ref([]);
// 供应商远端搜索
const supplierSearch = async (query: string) => {
  if (query) {
    try {
      const response = await axiosInstance.post(`/api/basedataSupplier/getPage`, {
        current: 1,
        pageSize: 20,
        name: query
      });
      supplierList.value = await response.data.records; // 假设返回的数据直接是供应商列表
    } catch (error) {
      supplierList.value = []; // 出错时清空列表
    }
  }
};
const deviceList = ref([]);
const materialList = ref([]); // 物料表

const downLoading = ref(false);
const handleExport = () => {
  downLoading.value = true;
  axios.post('/api/purchaseinstocklog/exportExcel', {
    ...searchParam.value,
    startDate: searchParam.value?.times?.[0],
    endDate: searchParam.value?.times?.[1],
    times: undefined,
    ...{
      type: 0
    }
  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', '出入库记录' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};


const getOption = () => {
  axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    wareList.value = res.data;
  });
  axiosInstance.post('/api/basedataMaterial/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        materialList.value = res.data;
      });

  axiosInstance.post('/api/basedataStorage/getAll', {})
      .then(res => {
        storageList.value = res.data;
        sourceStorageId_out.value = res.data;
      });

  // axiosInstance.post('/api/basedataEquipment/getAll', {})
  //   .then((res) => {
  //     if (res.code !== 200) {
  //       ElMessage.warning(res.message);
  //       return false;
  //     }
  //     deviceList.value = res.data;
  //   });

  // axiosInstance.post('/api/outsourcingPlan/querySourcingPlanProcedureOrder', {})
  //   .then(res => {
  //     workOrderList.value = res.data;
  //   });

  // // 查询所有库位
  // axiosInstance.post('/api/basedataStorage/getAll', {})
  //   .then(res => {
  //     storageAllList.value = res.data;
  //   });


  // axiosInstance.post(`/api/basedataSupplier/getPage`, {
  //   current: 1,
  //   pageSize: 20
  // }).then(res => {
  //   if (res.code == 200) {
  //     supplierList.value = res.data.records;
  //   }
  // });


  // axiosInstance.post('/api/planProcedureOrder/getAll', {})
  //   .then(res => {
  //     if (res.code !== 200) {
  //       ElMessage.error(res.message);
  //       return false;
  //     }
  //     const list = res.data;
  //     const loop = [];
  //     for (const item of list) {
  //       loop.push(
  //         {
  //           value: item.id,
  //           label: item.materialName
  //         }
  //       );
  //     }
  //     procedureOrderList.value = list;
  //   });

  // axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
  //   if (res.code !== 200) {
  //     ElMessage.error(res.message);
  //     return false;
  //   }
  //   wareList.value = res.data;
  // });
};

const storageList = ref([]);
const sourceStorageId_out = ref([]);
const wareChange = (e, type) => {
  if (!e) {
    searchParam.value.targetStorageId = [];
    axiosInstance.post('/api/basedataStorage/getAll', {})
        .then(res => {
          storageList.value = res.data;
          // sourceStorageId_out.value = res.data;
        });
    return;
  }
  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: e,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        storageList.value = res.data.records;
        searchParam.value.targetStorageId = storageList.value.map(item => item.id);
      });
};
const wareChange2 = (e, type) => {
  // storageList.value = {}
  if (!e) {
    searchParam.value.sourceStorageId = [];
    axiosInstance.post('/api/basedataStorage/getAll', {})
        .then(res => {
          // storageList.value = res.data;
          sourceStorageId_out.value = res.data;
        });
    return;
  }
  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: e,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        sourceStorageId_out.value = res.data.records;
        searchParam.value.sourceStorageId = sourceStorageId_out.value.map(item => item.id);
      });
};
// 获取列表接口
const getList = () => {
  axiosInstance.post('/api/purchaseinstocklog/getPage', {
    ...searchParam.value,
    ...pageSearch.value,
    startDate: searchParam.value?.times?.[0],
    endDate: searchParam.value?.times?.[1],
    times: undefined,
    ...{
      type: 0
    }
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        const list = res.data.records;
        for (const item of list) {
          item.children = item.outsourcingWorkMaterialVOS;
        }
        paginatedData.value = list;
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  // current.value = 1
  getList();
};

</script>
<style scoped></style>
